package com.bgs.eat.config;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bgs.eat.chat.entity.ChatRecordEntity;
import com.bgs.eat.chat.service.ChatRecordService;
import com.bgs.eat.utils.LobbyMessages;
import com.bgs.eat.utils.Message;
import com.bgs.eat.utils.MyDateUtil;
import com.bgs.eat.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/dchat/{id}/{device}")
@Component
public class SocketServer {

    ///用来保存,用户的session
    public static Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    private static  RedisOperator redisOperator;

    @OnOpen
    public void onOpen(Session session, @PathParam("id")String id,@PathParam("device") String device){
        System.out.println(id);
         //日志
        System.out.println("用户："+id+"上线了\t"+ MyDateUtil.simpleDateFormat.format(new Date())+"\t使用设备:"+device);
        Session cacheSession = sessionMap.get(id);
        if(cacheSession==null){
            //不存在session则说明用户没有登录过   缓存用户的session
            sessionMap.put(id,session);
            System.out.println(sessionMap.put(id,session));
        }
        else{
                if(!Objects.equals(cacheSession.getId(), session.getId())) {
                    //用户在其他的设备上登录   挤下线
                    //覆盖原来的session
                    sessionMap.put(id, cacheSession);
                }
        }
        //在线人数
//        this.sendAllMessage(JSONUtil.toJsonStr(new Message<>(200,"online-num",sessionMap.size())));
        System.out.println("当前在线人数："+sessionMap.size());
        // 在线的人分别是谁
        System.out.println(sessionMap.keySet()+"\n");
    }
    @OnClose
    public void onClose(Session session,@PathParam("id") String id){
        Session cacheSession = sessionMap.get(id);
        if(ObjectUtils.isEmpty(cacheSession)){
            System.out.println("用户："+id+"正常下线\t"+MyDateUtil.simpleDateFormat.format(new Date()));
            System.out.println("当前在线人数："+sessionMap.size());
            System.out.println(sessionMap.keySet()+"\n");
            return;
        }
        try {
            cacheSession.close();
            sessionMap.remove(id);
        } catch (IOException e) {
            System.out.println("关闭连接出现错误");
        }

        //在线人数
        this.sendAllMessage(JSONUtil.toJsonStr(new Message<>(200,"online-num",sessionMap.size())));

        System.out.println("用户："+id+"正常下线\t"+MyDateUtil.simpleDateFormat.format(new Date()));
        System.out.println("当前在线人数："+sessionMap.size());
        System.out.println(sessionMap.keySet()+"\n");
    }
    @OnError
    public void onError(Session session,Throwable error,@PathParam("id") String id){
        Session cacheSession = sessionMap.get(id);
        if(ObjectUtils.isEmpty(cacheSession)){
            System.out.println("用户："+id+"异常下线\t"+MyDateUtil.simpleDateFormat.format(new Date()));
            System.out.println("当前在线人数："+sessionMap.size());
            System.out.println(sessionMap.keySet()+"\n");
            return;
        }
        try {
            cacheSession.close();
            sessionMap.remove(id,cacheSession);
        } catch (IOException e) {
            System.out.println("关闭连接出现错误");
        }

        //error.printStackTrace();

        System.out.println("用户："+id+"异常下线\t"+MyDateUtil.simpleDateFormat.format(new Date()));
        System.out.println("当前在线人数："+sessionMap.size());
        System.out.println(sessionMap.keySet()+"\n");
    }
    @OnMessage
    public void onMessage(String message,Session session,@PathParam("id") String id){
        JSONObject data = JSONUtil.parseObj(message);
        switch (data.getStr("type")){
            // 浏览器定时给服务器发送请求防止短线
            case "ping":
                Message<String> response = new Message<>(200,"pong","success");
                this.sendMessage(JSONUtil.toJsonStr(response),session);
                break;
            case "person_message":
                String toId = data.getStr("to");
                ChatRecordService chatRecordService = SpringContextUtil.getBean(ChatRecordService.class);
                int i = chatRecordService.insertChatRecord(data);
                this.sendMessageById(toId,message);
                break;
//            case "delete-person":
//                this.deletePerson(data,session);
//                break;
            case "lobby-message":
                this.lobbyMessage(message,session);
                break;
//            case "group_message":
//                this.groupMessage(message,session);
//                break;
//            case "quit-group":
//                this.quitGroup(data,session);
//                break;
//            case "kick-person":
//                this.kickPerson(data,session);
//                break;
//            case "invite-people":
//                this.invitePeople(data);
//                break;
        }
    }
    //处理删除请求
    private void lobbyMessage(String message,Session session){
        redisOperator.cacheLobbyMessage(JSONUtil.parseObj(message).getStr("message"));
        this.sendAllMessage(message);
    }
    private void sendMessageById(String id,String message){
        for(String key:sessionMap.keySet()){
            if(key.equals(id)){
                this.sendMessage(message,sessionMap.get(key));
                return;
            }
        }
        //如果收信人不在线，则将信息进行缓存
//        redisOperator.cacheMessages(id,message);
    }
    //发送消息给某个用户
    private void sendMessage(String message,Session toSession){
        try {
            if(toSession.isOpen()){
                System.out.println("发送成功");
                toSession.getBasicRemote().sendText(message);
            }

        }catch (Exception e){
            System.out.println("发送失败");
            e.printStackTrace();
        }
    }
    // 将当前在线人数发送给每个浏览器（用户）
    private void sendAllMessage(String message){
        try {
            for(Session session : sessionMap.values()){
                if (session.isOpen()) {
                    session.getBasicRemote().sendText(message);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
